<?php
class system_passport_storage_cookie extends system_passport_storage_abstract {

	public function __construct($namespance) {
		parent::__construct($namespance);
	}
	
	public function save() {
		$value = serialize(array(system_passport::$_name => serialize($this->_data)));
		$expire = intval(time() + $this->_sessionOptions['remember_me_seconds']);
		$this->setCookie($value, $expire);
		return $this;
	}
	
	public function clean() {
		$this->setCookie(false, 0);
		$this->_data = null;
		return $this;
	}
	
	public function readData() {
		if($this->_data === null) {
			$data = system_controller_front::getInstance()->getRequest()->getCookie($this->_namespace);
			$data = !empty($data) ? unserialize($data) : null;
			if(is_array($data) && isset($data[system_passport::$_name])) {
				$this->_data = unserialize($data[system_passport::$_name]);
			}
		}
		return $this->_data;
	}
	
	private function setCookie($data, $expire) {
		return setcookie(
				$this->_namespace, 
				$data, 
				$expire,  
				$this->_sessionOptions['cookie_path'], 
				$this->_sessionOptions['cookie_domain'], 
				$this->_sessionOptions['cookie_secure']
		);
	}
}